<?php
Class admin_hangsanxuatController Extends baseController {

	public function index() { 
		$hangsanxuatModel = new hangsanxuat();
		$current_page = (isset($_REQUEST['page'])) ? $_REQUEST['page'] : 1;
		$pos = ($current_page -1 ) * __PAGE_SIZE;
		$lstTv = $hangsanxuatModel->getHangsanxuatByWherePaging('', '',$pos);
		$count = count((array)$hangsanxuatModel->getAllHangSanXuatByWhere('', ''));
		$pages = ceil($count/__PAGE_SIZE);

		$this->registry->template->lstHang = $lstTv;
		$this->registry->template->pages = $pages;
		
		$this->registry->template->show('admin/hangsanxuat_view');
	}
	
	public function edit(){
		if(isset($_REQUEST['hang_id'])){
			$hang_id = $_REQUEST['hang_id'];
			$hangModel = new hangsanxuat();
			$tivi = $hangModel->getHangSanXuatById($hang_id);
			if(count($tivi)>0){
				$this->registry->template->hang = $tivi;	
			}
		}
		$this->registry->template->show('admin/hangsanxuat_edit');	
	}
	
	public function save(){
			
			$hang = new hangsanxuat();
			$hang->TenHang = trim($_POST['ttenhang']);
			$hang->TrangThai = $_POST['rtrangthai'];
			
			if(isset($_REQUEST['hang_id'])) $hang->id = trim($_GET['hang_id']);
			//else $hang->id = trim($_POST['ttendangnhap']);
			
			
			//lay danh sach user de kiem tra ten dang nhap va email xem da co chua
			if(isset($_REQUEST['hang_id'])) $lstHang = $hang->getAllHangSanXuatByWhere('id <> "'.$hang->id.'"','');
			else $lstHang = $hang->getAllHangSanXuatByWhere('','');
			if(count($lstHang)>0)
			{
				//kiem tra neu ton tai ten dang nhap do roi thi hien thong bao
				foreach($lstHang as $h){
					if((strtolower(trim($h->TenHang)) == strtolower(trim($hang->TenHang)))){
						$this->registry->template->message_user = 'Tên hãng đã tồn tại.';
						$this->registry->template->hang = $hang;
						$this->registry->template->show('admin/hangsanxuat_edit');
						return;	
					}
				}
			}
			if(isset($_REQUEST['hang_id'])){
				//$hang->id = $_GET['hang_id'];
				$rs = $hang->update($hang);
				if($hang->TrangThai == '0'){
					$tiviModel = new tivi();
					$tiviModel->updateTrangThaiByHang("0",$hang->id);
				}
			}
			else{
				
				$rs = $hang->insert($hang);
			}
			
			if($rs){
				echo '<script>alert("thành công.");</script>';
				header('location:'.__URL_BASE.'index.php?rt=admin_hangsanxuat');
				exit;
			}
			else{
				echo '<script>alert("Có lỗi xảy ra.");</script>';
			}
		}
		
		public function delete(){
			if(isset($_REQUEST['hang_id'])){
				$hangModel = new hangsanxuat();
				$hangModel->delete($_REQUEST['hang_id']);
				header('location:'.__URL_BASE.'index.php?rt=admin_hangsanxuat');
				exit;
			}
		}

}
?>
